package com.xbongbong.workflow.service.strategy.data.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.constant.TimeConstant;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.enums.FieldTypeEnum;
import com.xbongbong.paas.enums.FlowStatusEnum;
import com.xbongbong.paas.enums.IndexTypeEnum;
import com.xbongbong.paas.enums.PlatFormEnum;
import com.xbongbong.paas.enums.TaskTypeEnum;
import com.xbongbong.paas.pojo.dto.SaasFormSaveDTO;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.BeanUtil;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.toolbox.util.DateTimeUtil;
import com.xbongbong.paas.toolbox.util.StringUtil;
import com.xbongbong.paas.toolbox.wrap.UserVO;
import com.xbongbong.paas.util.FormDataUtil;
import com.xbongbong.pro.constant.BusinessConstant;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.formdata.pojo.SaasNeedRedundantAttrPojo;
import com.xbongbong.pro.workflow.enums.WorkflowOperateEnum;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.constant.ProductConstant;
import com.xbongbong.saas.constant.StringConstant;
import com.xbongbong.saas.domain.entity.ProductBaseInfoEntity;
import com.xbongbong.saas.domain.entity.ProductSerialBalanceEntity;
import com.xbongbong.saas.domain.entity.ProductSerialFlowEntity;
import com.xbongbong.saas.domain.entity.TransferProductEntity;
import com.xbongbong.saas.domain.entity.ext.TransferEntityExt;
import com.xbongbong.saas.enums.SelectProductEnum;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.enums.business.ProductEnum;
import com.xbongbong.saas.enums.business.SerialEnum;
import com.xbongbong.saas.enums.business.SerialStatusEnum;
import com.xbongbong.saas.enums.business.TransferEnum;
import com.xbongbong.saas.enums.dictionary.TransferTypeEnum;
import com.xbongbong.saas.enums.product.AssembleProductEnum;
import com.xbongbong.saas.enums.product.TransferProductEnum;
import com.xbongbong.saas.help.SaasSaveHelp;
import com.xbongbong.saas.help.workflow.ProductSerialHelp;
import com.xbongbong.saas.help.workflow.ProductValidateHelp;
import com.xbongbong.saas.model.PaasFormSubDataModel;
import com.xbongbong.saas.model.ProductBaseInfoModel;
import com.xbongbong.saas.model.ProductSerialBalanceModel;
import com.xbongbong.saas.model.ProductSerialFlowModel;
import com.xbongbong.saas.model.TransferModel;
import com.xbongbong.saas.model.TransferProductModel;
import com.xbongbong.saas.toolbox.help.FastJsonHelper;
import com.xbongbong.sys.domain.entity.UserEntity;
import com.xbongbong.sys.model.UserModel;
import com.xbongbong.util.ProductUtil;
import com.xbongbong.workflow.domain.entity.WorkflowBackupDataEntity;
import com.xbongbong.workflow.model.WorkflowBackupDataModel;
import com.xbongbong.workflow.pojo.Data;
import com.xbongbong.workflow.pojo.User;
import com.xbongbong.workflow.pojo.WorkflowTransferPOJO;
import com.xbongbong.workflow.service.strategy.data.AbstractWorkflowDataStrategy;
import com.xbongbong.workflow.service.strategy.data.WorkflowDataProcessStrategy;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 *
 * @author 魏荣杰
 *
 */
@Service
@Slf4j
public class WorkflowTransferStrategy extends AbstractWorkflowDataStrategy implements WorkflowDataProcessStrategy {

    @Resource
    private ProductValidateHelp productValidateHelp;
    @Resource
    private SaasSaveHelp saasSaveHelp;
    @Resource
    private UserModel userModel;
    @Resource
    private TransferModel transferModel;
    @Resource
    private WorkflowBackupDataModel workflowBackupDataModel;
    @Resource
    private TransferProductModel transferProductModel;
    @Resource
    private ProductBaseInfoModel productBaseInfoModel;
    @Resource
    private ProductSerialFlowModel productSerialFlowModel;
    @Resource
    private ProductSerialBalanceModel productSerialBalanceModel;
    @Resource
    private ProductSerialHelp productSerialHelp;
    @Resource
    private PaasFormSubDataModel paasFormSubDataModel;

    @Override
    public List<Integer> type() {
        return Collections.singletonList(XbbRefTypeEnum.TRANSFER.getCode());
    }

    @Override
    public void save(WorkflowTransferPOJO workflowTransferPOJO, SaasNeedRedundantAttrPojo saasNeedRedundantAttrPojo) throws XbbException {
        // 文件柜
        saveDataCabinetFile(workflowTransferPOJO);

        String corpid = workflowTransferPOJO.getCorpid();
        Data pojoData = workflowTransferPOJO.getData();
        Long formId = pojoData.getFormId();
        JSONObject data = pojoData.getData();
        Long dataId = pojoData.getId();
        User user = workflowTransferPOJO.getUser();
        UserEntity userEntity = userModel.getByKeyIngoreDel(user.getUserId(), corpid);
        UserVO userVO = new UserVO();
        BeanUtil.copyProperties(userEntity, userVO);

        String transferType = FastJsonHelper.getStringOrDefaultFromFormData(data, TransferEnum.TRANSFER_TYPE.getAttr(), TransferTypeEnum.UNLOCAL_TRANSFER.getCode());
        JSONArray productArray = data.getJSONArray(TransferEnum.PRODUCTS.getAttr());
        Long intoWarehouseId = FastJsonHelper.getLongOrDefaultFromFormData(data, TransferEnum.INTO_WAREHOUSE_ID.getAttr(), 0L);
        Long outWarehouseId = FastJsonHelper.getLongOrDefaultFromFormData(data, TransferEnum.OUT_WAREHOUSE_ID.getAttr(), 0L);


        List<TransferProductEntity> transferProductEntities = transferProductModel.getProductsByTransferId(dataId, corpid);
        Map<Long, TransferProductEntity> transferProductMap = new HashMap<>(transferProductEntities.size());
        transferProductEntities.forEach(item->{
            transferProductMap.put(item.getId(), item);
        });
        List<ProductBaseInfoEntity> addProductBaseInfoList = new ArrayList<>();
        List<ProductSerialFlowEntity> productSerialFlowEntityList = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        List<String> seqKeyList = new ArrayList<>();
        Map<String, ProductSerialFlowEntity> productSerialFlowEntityMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        // 完成工作流，将序列号插入到序列号流水表，并且更新结存表
        for (int i =0; i< productArray.size(); i++ ) {
            JSONObject jsonObject = productArray.getJSONObject(i);

            if (StringUtil.isNotEmpty(jsonObject.getString(TransferProductEnum.BATCH.getAttr()))) {
                Long refProductId = jsonObject.getLong(BusinessConstant.REF_PRODUCT_ID);
                TransferProductEntity transferProductEntity = transferProductMap.get(refProductId);
                // 处理产品baseinfo
                ProductBaseInfoEntity productBaseInfoEntity = new ProductBaseInfoEntity();
                productBaseInfoEntity.setCorpid(corpid);
                productBaseInfoEntity.setFormId(formId);
                productBaseInfoEntity.setRefId(jsonObject.getLong(BusinessConstant.REF_PRODUCT_ID));
                productBaseInfoEntity.setRefType(XbbRefTypeEnum.TRANSFER_PRODUCT.getCode());
                productBaseInfoEntity.setBatch(transferProductEntity.getBatch());
                productBaseInfoEntity.setProduceDate(transferProductEntity.getProduceDate());
                if (Objects.nonNull(transferProductEntity.getGuaranteePeriod())) {
                    productBaseInfoEntity.setGuaranteePeriod(transferProductEntity.getGuaranteePeriod());
                }
                productBaseInfoEntity.setMemo(transferProductEntity.getMemo());
                productBaseInfoEntity.setData(jsonObject);
                productBaseInfoEntity.setDel(0);
                productBaseInfoEntity.setAddTime(DateTimeUtil.getInt());
                productBaseInfoEntity.setUpdateTime(DateTimeUtil.getInt());
                addProductBaseInfoList.add(productBaseInfoEntity);
            }
            if (CollectionsUtil.isNotEmpty(addProductBaseInfoList)) {
                productBaseInfoModel.insertBatch(addProductBaseInfoList);
            }

            // 处理产品序列号
            JSONArray seqArray = jsonObject.getJSONArray(ProductConstant.SEQ);
            if (ProductUtil.productSeqIsEmpty(jsonObject, seqArray)) {
                continue;
            }
            Long productId = jsonObject.getLong(SelectProductEnum.PRODUCT.getAttr());
            for (Object o : seqArray) {
                JSONObject seqData = (JSONObject) o;
                String serial = seqData.getString(SerialEnum.SERIAL.getAttr());
                String seqKey = productId + StringConstant.UNDER_LINE + serial;

                ProductSerialFlowEntity productSerialFlowEntity = new ProductSerialFlowEntity();
                productSerialFlowEntity.setCorpid(corpid);
                productSerialFlowEntity.setProductId(productId);
                productSerialFlowEntity.setSeq(serial);
                productSerialFlowEntity.setStatus(SerialStatusEnum.IN_STOCK.getCode());
                productSerialFlowEntity.setMemo(seqData.getString(SerialEnum.MEMO.getAttr()));
                productSerialFlowEntity.setDate(DateTimeUtil.getInt());
                productSerialFlowEntity.setBusinessType(XbbRefTypeEnum.TRANSFER.getCode());
                productSerialFlowEntity.setRefId(dataId);
                productSerialFlowEntity.setRefSheetNo(data.getString(FieldTypeEnum.SERIALNO.getAlias()));
                // 关联产品id
                Long refProductId = jsonObject.getLong(BusinessConstant.REF_PRODUCT_ID);
                productSerialFlowEntity.setRefProductId(refProductId);
                productSerialFlowEntity.setParentId(transferProductMap.get(refProductId).getParentId());
                // 调拨出入库仓库数据
                productSerialFlowEntity.setWarehouseName(data.getString(TransferEnum.OUT_WAREHOUSE_ID_LINKED_TEXT.getAttr()));
                productSerialFlowEntity.setWarehouseId(data.getLong(TransferEnum.OUT_WAREHOUSE_ID.getAttr()));
                productSerialFlowEntity.setSeqKey(seqKey);
                productSerialFlowEntity.setDel(BasicConstant.ZERO);

                seqKeyList.add(seqKey);
                productSerialFlowEntityList.add(productSerialFlowEntity);
                productSerialFlowEntityMap.put(productSerialFlowEntity.getSeqKey(), productSerialFlowEntity);
            }
        }

        if (CollectionsUtil.isNotEmpty(productSerialFlowEntityList)) {
            Map<String, Object> param = new HashMap<>();
            param.put("corpid", corpid);
            param.put(StringConstant.DEL, DelEnum.NORMAL.getDel());
            param.put("seqKeyIn", seqKeyList);
            List<ProductSerialBalanceEntity> entitys = productSerialBalanceModel.findEntitys(param);
            for (ProductSerialBalanceEntity entity : entitys) {
                ProductSerialFlowEntity productSerialFlowEntity = productSerialFlowEntityMap.get(entity.getSeqKey());
                entity.setStatus(productSerialFlowEntity.getStatus());
                entity.setBusinessType(productSerialFlowEntity.getBusinessType());
                entity.setRefSheetNo(productSerialFlowEntity.getRefSheetNo());
                entity.setRefId(productSerialFlowEntity.getRefId());
                entity.setRefProductId(productSerialFlowEntity.getRefProductId());
                entity.setDate(productSerialFlowEntity.getDate());

                productSerialFlowEntity.setWarehouseId(entity.getWarehouseId());
                productSerialFlowEntity.setBusinessId(entity.getBusinessId());
                productSerialFlowEntity.setBusinessName(entity.getBusinessName());
            }
            productSerialBalanceModel.updateBatch(entitys, corpid);
            productSerialFlowModel.insertBatch(productSerialFlowEntityList);
        }



        //新建本地调拨走下面的逻辑
        if (Objects.equals(transferType, TransferTypeEnum.LOCAL_TRANSFER.getCode())) {
            // 本地调拨出入库的关联产品取调拨单出库仓库的产品
            Map<Object,Double> costMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            Map<Object,Double> stockMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            productValidateHelp.getSkuWarehouseOrBatchCost(productArray, outWarehouseId, corpid, costMap, stockMap);

            TransferEntityExt transferEntityExt = transferModel.getByKey(dataId, corpid);
            transferEntityExt.setData(data);
            SaasFormSaveDTO saasFormSaveDTO = new SaasFormSaveDTO();
            saasFormSaveDTO.setCorpid(corpid);
            saasFormSaveDTO.setBusinessType(pojoData.getBusinessType());
            saasFormSaveDTO.setOldData(data);
            saasFormSaveDTO.setNewData(data);
            saasFormSaveDTO.setNewPaasFormDataEntity(transferEntityExt);
            saasFormSaveDTO.setOldPaasFormDataEntity(transferEntityExt);
            saasFormSaveDTO.setIsNew(true);
            saasFormSaveDTO.setIsImport(workflowTransferPOJO.getIsImport());
            saasFormSaveDTO.setCostMap(costMap);
            saasFormSaveDTO.setLoginUser(userVO);
            saasFormSaveDTO.setUserId(user.getUserId());
            saasFormSaveDTO.setLoginUserName(user.getName());
            saasFormSaveDTO.setPlatform(PlatFormEnum.INTERNAL.getValue());

            saasSaveHelp.generateStockSheet(saasFormSaveDTO);

//            SaasFormSaveDTO saasFormSaveDT1 = (SaasFormSaveDTO) CloneUtil.deepClone(saasFormSaveDTO);
//            try {
//                // 生成出库单
//                outstockService.generateOutStockSheet(saasFormSaveDTO);
//                // 生成入库单
//                instockService.generateInStockSheet(saasFormSaveDT1);
//            } catch (Exception e) {
//                log.error("TransferServiceImpl.afterSave.generateStockSheet 执行出错：", e);
//            }
        }

        // api
        apiHook(workflowTransferPOJO);
        addLinkDataDynamic(workflowTransferPOJO);
        // log
        afterSaveLog(workflowTransferPOJO);
    }

    @Override
    public void update(WorkflowTransferPOJO workflowTransferPOJO, SaasNeedRedundantAttrPojo saasNeedRedundantAttrPojo) throws XbbException {
        // 文件柜
        saveDataCabinetFile(workflowTransferPOJO);

        String corpid = workflowTransferPOJO.getCorpid();
        Data pojoData = workflowTransferPOJO.getData();
        JSONObject data = pojoData.getData();
        Long dataId = pojoData.getId();

        WorkflowBackupDataEntity workflowBackupDataEntity = workflowBackupDataModel.getByKey(workflowTransferPOJO.getBackupDataId(), corpid);
        JSONObject oldData = workflowBackupDataEntity.getData();
        List<TransferProductEntity> oldTransferProducts = JSON.parseArray(oldData.getString(StringConstant.PRODUCT), TransferProductEntity.class);
        Map<Long, TransferProductEntity> oldProductMap = new HashMap<>();
        oldTransferProducts.forEach(v -> oldProductMap.put(v.getId(), v));
        // 处理baseinfo和序列号
        List<TransferProductEntity> transferProductEntities = transferProductModel.getProductsByTransferId(dataId, corpid);
        Map<Long, ProductBaseInfoEntity> oldBaseInfoMap = new HashMap<>();
        if (CollectionsUtil.isNotEmpty(oldTransferProducts)) {
            List<ProductBaseInfoEntity> productBaseInfoList = productBaseInfoModel.getProductBaseInfoList(corpid, XbbRefTypeEnum.TRANSFER_PRODUCT.getCode(), oldProductMap.keySet());
            productBaseInfoList.forEach(v -> oldBaseInfoMap.put(v.getRefId(), v));
        }

        // 新增产品
        List<TransferProductEntity> addProductList = new ArrayList<>();
        // 新增
        List<ProductBaseInfoEntity> addProductBaseInfoList = new ArrayList<>();
        // 编辑
        List<ProductBaseInfoEntity> updateProductBaseInfoList = new ArrayList<>();
        for (TransferProductEntity transferProductEntity : transferProductEntities) {
            JSONObject jsonObject = transferProductEntity.getData();
            if (oldProductMap.containsKey(transferProductEntity.getId())) {
                // 编辑
                ProductBaseInfoEntity productBaseInfoEntity = oldBaseInfoMap.get(transferProductEntity.getId());
                if (Objects.nonNull(productBaseInfoEntity)) {
                    productBaseInfoEntity.setBatch(jsonObject.getString(TransferProductEnum.BATCH.getAttr()));
                    productBaseInfoEntity.setProduceDate(jsonObject.getLong(AssembleProductEnum.PRODUCE_DATE.getAttr()));
                    if (Objects.nonNull(jsonObject.getLong(TransferProductEnum.GUARANTEE_PERIOD.getAttr()))){
                        productBaseInfoEntity.setGuaranteePeriod(jsonObject.getLong(TransferProductEnum.GUARANTEE_PERIOD.getAttr()) * TimeConstant.SECONDS_PER_DAY);
                    }
                    productBaseInfoEntity.setMemo(jsonObject.getString(TransferProductEnum.MEMO.getAttr()));
                    updateProductBaseInfoList.add(productBaseInfoEntity);
                }
                oldProductMap.remove(transferProductEntity.getId());
            } else {
                // 新增
                ProductBaseInfoEntity productBaseInfoEntity = new ProductBaseInfoEntity();
                productBaseInfoEntity.setCorpid(corpid);
                productBaseInfoEntity.setFormId(transferProductEntity.getFormId());
                productBaseInfoEntity.setRefId(transferProductEntity.getId());
                productBaseInfoEntity.setRefType(XbbRefTypeEnum.TRANSFER_PRODUCT.getCode());
                productBaseInfoEntity.setBatch(jsonObject.getString(TransferProductEnum.BATCH.getAttr()));
                productBaseInfoEntity.setProduceDate(jsonObject.getLong(AssembleProductEnum.PRODUCE_DATE.getAttr()));
                if (Objects.nonNull(jsonObject.getLong(TransferProductEnum.GUARANTEE_PERIOD.getAttr()))){
                    productBaseInfoEntity.setGuaranteePeriod(jsonObject.getLong(TransferProductEnum.GUARANTEE_PERIOD.getAttr()) * TimeConstant.SECONDS_PER_DAY);
                }
                productBaseInfoEntity.setMemo(jsonObject.getString(TransferProductEnum.MEMO.getAttr()));
                productBaseInfoEntity.setData(jsonObject);
                productBaseInfoEntity.setDel(0);
                productBaseInfoEntity.setAddTime(DateTimeUtil.getInt());
                productBaseInfoEntity.setUpdateTime(DateTimeUtil.getInt());

                addProductBaseInfoList.add(productBaseInfoEntity);
                addProductList.add(transferProductEntity);
            }
        }
        if (CollectionsUtil.isNotEmpty(addProductBaseInfoList)) {
            productBaseInfoModel.insertBatch(addProductBaseInfoList);
        }
        if (CollectionsUtil.isNotEmpty(updateProductBaseInfoList)) {
            productBaseInfoModel.updateBatch(updateProductBaseInfoList, corpid);
        }
        List<Long> delRefIdList = new ArrayList<>();
        for (Map.Entry<Long, TransferProductEntity> entry : oldProductMap.entrySet()) {
            TransferProductEntity delProduct = entry.getValue();
            // 删除序列号
            productSerialFlowModel.delByRefProductAndBusinessType(corpid, delProduct.getId(), XbbRefTypeEnum.TRANSFER.getCode());
            // 删除调拨产品
            transferProductModel.deleteByKey(delProduct.getId(), delProduct.getCorpid());
            delRefIdList.add(delProduct.getId());
        }
        if (!delRefIdList.isEmpty()){
            productBaseInfoModel.deleteByRefIds(corpid,delRefIdList,XbbRefTypeEnum.TRANSFER_PRODUCT.getCode());
        }

        // 序列号处理
        List<ProductSerialFlowEntity> flowEntityList = productSerialFlowModel.getFlowByRefIdAndBusiness(Collections.singletonList(dataId), XbbRefTypeEnum.TRANSFER.getCode(), corpid);
        List<String> serialList = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        if (CollectionUtils.isNotEmpty(flowEntityList)) {
            flowEntityList.forEach(item -> serialList.add(item.getSeqKey()));
        }

        List<ProductSerialFlowEntity> productSerialFlowEntityList = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        List<String> seqKeyList = new ArrayList<>();
        Map<String, ProductSerialFlowEntity> productSerialFlowEntityMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        for (TransferProductEntity transferProductEntity : addProductList) {
            JSONObject productData = transferProductEntity.getData();
            Long productId = productData.getLong(SelectProductEnum.PRODUCT.getAttr());
            JSONArray seqArray = productData.getJSONArray(ProductConstant.SEQ);
            if (BasicConstant.ZERO.equals(productData.getIntValue(ProductEnum.ENABLE_SERIAL_NUMBER.getSaasAttr())) && (Objects.isNull(seqArray) || seqArray.isEmpty())) {
                continue;
            }
            for (Object o : seqArray) {
                JSONObject seqData = (JSONObject) o;
                String serial = seqData.getString(SerialEnum.SERIAL.getAttr());
                String seqKey = productId + StringConstant.UNDER_LINE + serial;
                if (serialList.contains(seqKey)) {
                    // TODO: 2021/8/3
                    continue;
                }
                ProductSerialFlowEntity productSerialFlowEntity = new ProductSerialFlowEntity();
                productSerialFlowEntity.setCorpid(corpid);
                productSerialFlowEntity.setProductId(productId);
                productSerialFlowEntity.setSeq(serial);
                productSerialFlowEntity.setMemo(seqData.getString(SerialEnum.MEMO.getAttr()));
                productSerialFlowEntity.setStatus(SerialStatusEnum.IN_STOCK.getCode());
                productSerialFlowEntity.setDate(DateTimeUtil.getInt());
                productSerialFlowEntity.setBusinessType(XbbRefTypeEnum.TRANSFER.getCode());
                productSerialFlowEntity.setRefId(dataId);
                productSerialFlowEntity.setRefSheetNo(data.getString(FieldTypeEnum.SERIALNO.getAlias()));
                // 关联产品id
                productSerialFlowEntity.setRefProductId(transferProductEntity.getId());
                productSerialFlowEntity.setParentId(transferProductEntity.getParentId());
                // 调拨出入库仓库数据
                productSerialFlowEntity.setWarehouseId(data.getLong(TransferEnum.OUT_WAREHOUSE_ID.getAttr()));
                productSerialFlowEntity.setWarehouseName(data.getString(TransferEnum.OUT_WAREHOUSE_ID_LINKED_TEXT.getAttr()));
                productSerialFlowEntity.setSeqKey(seqKey);
                productSerialFlowEntity.setDel(BasicConstant.ZERO);

                seqKeyList.add(seqKey);
                productSerialFlowEntityList.add(productSerialFlowEntity);
                productSerialFlowEntityMap.put(productSerialFlowEntity.getSeqKey(), productSerialFlowEntity);
            }
        }

        if (CollectionsUtil.isNotEmpty(productSerialFlowEntityList)) {
            Map<String, Object> param = new HashMap<>();
            param.put("corpid", corpid);
            param.put("seqKeyIn", seqKeyList);
            param.put(StringConstant.DEL, DelEnum.NORMAL.getDel());
            List<ProductSerialBalanceEntity> entitys = productSerialBalanceModel.findEntitys(param);
            for (ProductSerialBalanceEntity entity : entitys) {
                ProductSerialFlowEntity productSerialFlowEntity = productSerialFlowEntityMap.get(entity.getSeqKey());
                entity.setStatus(productSerialFlowEntity.getStatus());
                entity.setBusinessType(productSerialFlowEntity.getBusinessType());
                entity.setRefId(productSerialFlowEntity.getRefId());
                entity.setRefSheetNo(productSerialFlowEntity.getRefSheetNo());
                entity.setRefProductId(productSerialFlowEntity.getRefProductId());
                entity.setDate(productSerialFlowEntity.getDate());

                productSerialFlowEntity.setWarehouseId(entity.getWarehouseId());
                productSerialFlowEntity.setBusinessId(entity.getBusinessId());
                productSerialFlowEntity.setBusinessName(entity.getBusinessName());
            }
            productSerialBalanceModel.updateBatch(entitys, corpid);
            productSerialFlowModel.insertBatch(productSerialFlowEntityList);
        }


        // api
        apiHook(workflowTransferPOJO);
        // log
        afterUpdateLog(workflowTransferPOJO);
    }


    @Override
    public void updateBack(Long taskId, WorkflowTransferPOJO workflowTransferPOJO) throws XbbException {
        String corpid = workflowTransferPOJO.getCorpid();
        Long backupDataId = workflowTransferPOJO.getBackupDataId();
        Long dataId = workflowTransferPOJO.getData().getId();
        WorkflowBackupDataEntity workflowBackupDataEntity = workflowBackupDataModel.getByKey(backupDataId, corpid);
        if (Objects.nonNull(workflowBackupDataEntity)) {
            JSONObject data = workflowBackupDataEntity.getData();

            replenishAttrForBackupData(workflowTransferPOJO.getData().getData(), data);

            TransferEntityExt transferEntityExt = new TransferEntityExt();
            transferEntityExt.setId(dataId);
            transferEntityExt.setCorpid(corpid);
            transferEntityExt.setData(data);
            transferEntityExt.setSerialNo(data.getString(FieldTypeEnum.SERIALNO.getAlias()));
            transferEntityExt.setOwnerId(getOwnerId(data));
            transferEntityExt.setDepartmentId(data.getLong(FieldTypeEnum.DEPARTMENTID.getAlias()));

            List<TransferProductEntity> transferProductEntities = JSON.parseArray(data.getString(StringConstant.PRODUCT), TransferProductEntity.class);

            FormDataUtil.removeSystemData(data);
            data.remove(StringConstant.PRODUCT);
            if (Objects.equals(workflowTransferPOJO.getOperate(), WorkflowOperateEnum.UPDATE.getType())) {
                transferEntityExt.setFlowStatus(FlowStatusEnum.PASS.getType());
            }
            transferModel.update(transferEntityExt);
            // 回退被删掉的子表单
            updateBackSubForm(transferEntityExt, corpid, IndexTypeEnum.IDX_SAAS_TRANSFER_SUB);
            //回退被删掉的富文本
            updateBackRichText(taskId, workflowTransferPOJO);
            // 产品处理
            saveProduct(transferProductEntities, corpid, transferEntityExt.getId());

        }
    }

    @Override
    public void approvalFailed(Long taskId, WorkflowTransferPOJO workflowTransferPOJO, Integer taskType) throws XbbException {
        try {
            String corpid = workflowTransferPOJO.getCorpid();
            Data workflowData = workflowTransferPOJO.getData();
            Long dataId = workflowData.getId();
            Long formId = workflowData.getFormId();
            Integer businessType = workflowData.getBusinessType();
            Integer saasMark = workflowData.getSaasMark();
            TransferEntityExt supplierEntityExt = new TransferEntityExt();
            supplierEntityExt.setId(dataId);
            if (Objects.equals(TaskTypeEnum.REVOKE.getType(), taskType)) {
                supplierEntityExt.setFlowStatus(FlowStatusEnum.REVOKE.getType());
            } else {
                supplierEntityExt.setFlowStatus(FlowStatusEnum.REJECT.getType());
            }
            supplierEntityExt.setCorpid(corpid);
            supplierEntityExt.setUpdateTime(DateTimeUtil.getInt());
            transferModel.update(supplierEntityExt);
            // 子表单
            DelEnum del = DelEnum.APPROVE_FAILED;
            paasFormSubDataModel.deleteBatchByDataId(Collections.singletonList(dataId), corpid, IndexTypeEnum.IDX_SAAS_TRANSFER_SUB, del);
            //富文本
            deleteFormRichText(dataId, corpid, formId, businessType, saasMark, DelEnum.NORMAL);

            List<TransferProductEntity> products = transferProductModel.getProductsByTransferId(dataId, corpid);
            if (CollectionUtils.isNotEmpty(products)) {
                List<Long> delIds = new ArrayList<>();
                products.forEach(item->delIds.add(item.getId()));
                transferProductModel.deleteBatch(delIds, corpid, del.getDel());
            }
        } catch (Exception e) {
            log.error("com.xbongbong.workflow.service.strategy.data.impl.WorkflowTransferStrategy.approvalFailed error", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
        }
    }

    /**
     * Description: 产品还原
     * @param transferProductEntities 编辑前的产品
	 * @param corpid 公司id
	 * @param id transferId
     * @return void
     * @throws
     * @author 魏荣杰
     * @date 2021/8/3 10:48
     * @since
     */
    private void saveProduct(List<TransferProductEntity> transferProductEntities, String corpid, Long id) throws XbbException {
        try {

            List<Long> ids = new ArrayList<>();
            transferProductEntities.forEach(v -> ids.add(v.getId()));

            List<TransferProductEntity> products = transferProductModel.getProductsByTransferId(id, corpid);

            List<Long> delIds = products.stream().filter(v -> !ids.contains(v.getProductId())).map(TransferProductEntity::getId).collect(Collectors.toList());

            transferProductModel.deleteBatch(delIds, corpid, DelEnum.DELETE.getDel());

            transferProductModel.updateMulti(transferProductEntities, corpid);

        } catch (Exception e) {
            log.error("com.xbongbong.workflow.service.strategy.data.impl.WorkflowTransferStrategy.saveProduct error", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
        }
    }
}
